<?php
namespace control;

/*
*利润表类
*/

class profitIncomeClass extends adIndexClass
{
    private const page = 'profitIncome';
    private const title = '利润表';
    private const table = 'profit_income';
//    public function importData()
//    {
//         $fomatArray = [];//导入数据格式同一为TYPE_STRING
//            foreach ($this->importFieldInit() as $value){
//                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
//            }
//            $data = $this->importHead(format: $fomatArray);
//        $x = 0;
//        foreach ($data as $i => $row) {
//            if ($i>0){
//                $cell = formSubArray($row);
//                $field = [
//                    'id' => self::getId(),
//                    "accountRule" => 'enterpriseRule',
//                    'title'=>$cell[1],
//                    "type" => $cell[0],
//                    "name" => $cell[2],
//                    'pid'=>$cell[3],
//                    'formula'=>$cell[4]
//                ];
//                insert(["table" => 'profit_income_demo', "field" => $field]);
//                $x++;
//            }
//
//        }
//        $warn = "成功导入" . $x . "条数据，详情请查看日志！";
//        $_SESSION['warn'] = $warn;
//        header("Location:" . getenv("HTTP_REFERER"));
//        exit(0);
//    }


//    public function importData()
//    {
//         $fomatArray = [];//导入数据格式同一为TYPE_STRING
//            foreach ($this->importFieldInit() as $value){
//                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
//            }
//            $data = $this->importHead(format: $fomatArray);
//        $x = 0;
//        foreach ($data as $i => $row) {
//            if ($i>0){
//                $cell = formSubArray($row);
//                if ($cell[2]){
//                    $subject = query('subject',"code = '$cell[2]' and coid = '".self::$coid."'");
//                    $field = [
//                        'id' => self::getId(),
//                        "accountRule" => 'enterpriseRule',        //所属部门
//                        "name" => $cell[0],
//                        'subjectName'=>$subject['name'],//职位名称
//                        "subjectCode" => $cell[2],
//                        'symbol'=>$cell[3],
//                        'rule'=>$cell[4]
//                    ];
//                    insert(["table" => 'profit_income_formula_demo', "field" => $field]);
//                    $x++;
//                }
//            }
//        }
//        $warn = "成功导入" . $x . "条数据，详情请查看日志！";
//        $_SESSION['warn'] = $warn;
//        header("Location:" . getenv("HTTP_REFERER"));
//        exit(0);
//    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "month", 'laydate' => ['type' => 'month'], 'value' => date('Y-m'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //$button = $this->upButton(array("title" => "导入", "fun" => "importData"));
        //控件
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span class='spanButton'  onclick=\"window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage')\">打印</span>";
        }
        //返回
        return $this->homeFun($this->searchExecute([
            'html' => $html,
            'layout' => 'pop',
            'toolButton' => $button,
            'option' => '{fixed:true}'
        ]));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {

        $month = $this->post('month');
        static::rSet(self::$stid . self::page . 'Month', $month);
        $assetObj = new assetDebtClass();
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',[$month,$month]));
        $tr[] = array('项目', '行次', "本年累计金额", '本期金额'.$monthSelector['button']);
        $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = ''  order by list"));
        $list = 0;
        $accountRule = companyClass::returnRule(1);
        if($accountRule =='enterpriseRule'){
            foreach ($all['array'] as $array) {
                $dominate = '';
                if (!in_array($array['name'], ['营业利润', '利润总额', '净利润','其他综合收益的税后净额','综合收益总额'])) {
                    $result = $this->balance($array['name'], $month);
                    $dominate = $array['formula']?"<span class='del-row-button hide' style='margin-left:10px' onclick=\"layer('" . self::page . "','formula',{name:'" . $array['name'] . "'})\">公式</span>":'';
                } else {
                    $result = $this->totalProfit($array['name'], $month,$accountRule);
                }
                $list++;
                $tr[] = ["<span style='font-weight: bold'>{$array['title']}</span>" . $dominate, $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
                $res = $this->loopTr($array['name'], $list, $month, $assetObj);
                $tr = array_merge($tr, $res);
            }
        }elseif($accountRule =='smallEnterpriseRule'){
            foreach ($all['array'] as $array) {
                $dominate = '';
                if (!in_array($array['name'], ['营业利润', '利润总额', '净利润'])) {
                    $result = $this->balance($array['name'], $month);
                    $dominate = "<span class='del-row-button hide' style='margin-left:10px' onclick=\"layer('" . self::page . "','formula',{name:'" . $array['name'] . "'})\">公式</span>";
                } else {
                    $result = $this->totalProfit($array['name'], $month,$accountRule);
                }
                $list++;
                $tr[] = ["<span style='font-weight: bold'>{$array['title']}</span>" . $dominate, $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
                $res = $this->loopTr($array['name'], $list, $month, $assetObj);
                $tr = array_merge($tr, $res);
            }
        }

        $assetObj = new assetDebtClass();
        //返回
        $json['html'] =
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $this->tableMany(array("tr" => $tr,"displayFields" => false)) .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->js() .
            $this->css() .
            $assetObj->tableCss() .
            clear;
        return json_encode($json, 320);
    }
    public function css()
    {
        return <<<eof
<style>
.tableMany{
  table-layout: fixed;
}
.table_many_shell > .tableMany tr:nth-child(1) td:nth-child(1){
   width: 600px;
}
.tableMany td:nth-child(1) {
    width: auto;
}
</style>
eof;

    }

    /**
     * @param $name
     * @param $month
     * @param $accountRule
     * @return array
     */
    public function totalProfit($name, $month,$accountRule): array
    {
        $money = $monthMoney = 0;
        if ($name == '营业利润') {
            $result = $this->balance('营业收入', $month);
            $all = find(array('table' => self::table, 'where' => "pid = '营业收入' and coid = '" . self::$coid . "'"));
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
            if ($accountRule =='enterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month);
                    if (in_array($array['name'],['投资收益','公允价值变动收益'])) {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }elseif($accountRule =='smallEnterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month);
                    if ($array['name'] == '投资收益') {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }

        } elseif ($name == '利润总额') {
            $result = $this->totalProfit('营业利润', $month,$accountRule);
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
            $all = find(array('table' => self::table, 'where' => "pid = '营业利润' and coid = '" . self::$coid . "'"));
            if ($accountRule =='enterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month);
                    if (in_array($array['name'], ['营业外收入'])) {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }elseif($accountRule =='smallEnterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month);
                    if (in_array($array['name'], ['营业外收入', '政府补助'])) {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }

        } elseif ($name == '净利润') {
            $result = $this->totalProfit('利润总额', $month,$accountRule);
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
            $all = find(array('table' => self::table, 'where' => "pid = '利润总额' and coid = '" . self::$coid . "'"));
            foreach ($all['array'] as $array) {
                $result = $this->balance($array['name'], $month);
                $money -= $result['balance'];
                $monthMoney -= $result['monthBalance'];
            }
        }elseif($name == '其他综合收益的税后净额'){
            $money = 0;
            $monthMoney = 0;
        }elseif($name =='综合收益总额'){
            $result = $this->totalProfit('净利润', $month,$accountRule);
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
        }
        return ['balance' => $money, 'monthBalance' => $monthMoney];
    }

    /**
     * 公式
     * @return bool|string
     */
    public function formula(): bool|string
    {
        $name = $this->post('name');
        $tr[] = ['科目名称', '运算符号', '取数规则', '操作'];
        $all = find(array('table' => 'profit_income_formula', 'where' => "name = '$name' and coid = '" . self::$coid . "' order by time "));
        foreach ($all['array'] as $array) {
            $subject = query('subject', "id = '$array[subjectId]'");
            $tr[] = [$subject['code'].'-'.$subject['name'], $array['symbol'], $array['rule'], "<span class='del-row-button' onclick=\"delThis(this,'$array[id]')\">删除</span>"];
        }
        $symbol = select(array('name' => 'symbol', 'class' => 'select', 'option' => ['+', '-'], 'value' => '+'));
        $rule = select(array('name' => 'rule', 'class' => 'select', 'option' => ['贷方发生额','发生额','期初余额'], 'value' => '发生额'));
        $subjectSelect = componentClass::subjectSelect();
        $html = <<<eof
<form name="formulaForm">
    <div class="search" style="padding: 0 0 10px 0;">科目：$subjectSelect&emsp;&emsp;运算符号：{$symbol}&emsp;&emsp;取值：$rule&emsp;&emsp;
        <input name="profitName" type="hidden" value="$name">
        <input type="button" onclick="addRow()" class="searchSub" value="添加">
    </div>
</form>
eof;

        $html = "<div style='padding: 10px 10px 0 10px' id='formula'>" . $html . $this->tableMany(['tr' => $tr, 'end' => true]) . "</div>";
        return $this->layer(array("title" => "公式-".$name, "height" => 500, 'width' => 1000, "html" => $html, "button" => false));
    }

    public function addRow()
    {

        $field = [
            'id' => suiji(),
            'coid' => self::$coid,
            'name' => $this->post('profitName'),
            'symbol' => $this->post('symbol'),
            'subjectId' => $this->post('subjectId'),
            'rule' => $this->post('rule'),
        ];
        $annotation = [
            'id' => 'ID',
            'coid' => '账套ID',
            'name' => '名称',
            'symbol' => '运算符号',
            'subjectId' => '科目',
            'rule' => '取值',
        ];
        $rules = [
            'id' => 'required',
            'coid' => 'required',
            'name' => 'required',
            'symbol' => 'required',
            'subjectId' => 'required',
            'rule' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        } elseif (static::total(array('table' => 'profit_income_formula', 'where' => "name = '$field[name]' and coid = '" . self::$coid . "' and subjectId = '$field[subjectId]'")) > 0) {
            $json['warn'] = '已存在此科目';
        } else {
            $json['warn'] = static::insert(["table" => 'profit_income_formula', "field" => $field]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "," . $field['name'] . '的科目：' . subjectClass::getName($field['subjectId']);
                $this->logText(["type" => self::page, "text" => $text]);
                $subject = query('subject', "id = '$field[subjectId]'");
                //返回
                $json['warn'] = 2;
                $json['html'] = $this->tableMany([
                    'tr' => [
                        [$subject['code'].'-'.$subject['name'], $field['symbol'], $field['rule'], "<span class='del-row-button' onclick=\"delThis(this,'$field[id]')\">删除</span>"]
                    ],
                    'thead' => false,
                ]);
            }
        }
        resp:
        return json_encode($json, 320);
    }

    public function delRow()
    {
        $id = $this->post('id');
        if (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $info = query('profit_income_formula', "id = '$id'");
            $json['warn'] = delete(array('table' => 'profit_income_formula', 'where' => "id = '$id'"));
            if ($json['warn'] == '删除成功') {
                $text = $this->control['name'] . "删除了" . self::title . "," . $info['name'] . '的科目：' . subjectClass::getName($info['subjectId']);
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    public function loopTr($pid, &$list, $month, $assetObj,$isExport = false): array
    {
        $tr = [];
        $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '$pid' order by list"));
        foreach ($all['array'] as $array) {
            $list++;
            $dominate = "<span class='del-row-button hide' style='margin-left:10px' onclick=\"layer('" . self::page . "','formula',{name:'" . $array['name'] . "'})\">公式</span>";
            if ($isExport) {
                $dominate = '';
            }
            $result = $this->balance($array['name'], $month);
            if (!in_array($array['pid'], ['营业利润', '利润总额', '营业收入','其他综合收益的税后净额','综合收益总额'])) {
                $title = "&emsp;&emsp;" . $array['title'];
                if ($isExport){
                    $title = "    ". $array['title'];
                }
            }else{
                $title = "&emsp;" . $array['title'];
                if ($isExport){
                    $title = "  ". $array['title'];
                }
            }

            $tr[] = [$title. $dominate, $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
            $res = $this->loopTr($array['name'], $list, $month, $assetObj,$isExport);
            $tr = array_merge($tr, $res);
        }
        return $tr;
    }


    private function js()
    {
        return <<<eof
<script>
$(".tableMany tr").hover(function(){
    $(this).find(".del-row-button").show();
},function(){
      $(this).find(".del-row-button").hide();
});
function delThis(e,id){
     $.post(root+'control/adIndex.html?cla=profitIncome&fun=delRow',{id:id},function(res) {
       if (res.warn ===2){
          $(e).parent().parent().remove();
           return true;
       }
       msg(res.warn,'error')
    },'json')
}
function addRow(){
    $.post(root+'control/adIndex.html?cla=profitIncome&fun=addRow',$("[name='formulaForm']").serialize(),function(res) {
       if (res.warn ===2){
           $("#formula .tableMany tbody").append(res.html);
           return true;
       }
       msg(res.warn,'error')
    },'json')
}
</script>
eof;

    }

    /**
     * 期末余额
     */
    public function balance($name, $month)
    {

        $all = find(array('table' => 'profit_income_formula', 'where' => "name = '$name' and coid = '" . self::$coid . "'"));
        $grandTotalBalance = 0;//本年累计余额
        $monthBalance = 0;//本期金额
        $multObj = new multiColumnAccountClass();
        foreach ($all['array'] as $array) {
            $childGrandTotalBalance = 0;
            $childMonthBalance = 0;
            $columns=[];
            $multObj->loopSubjectIds($array['subjectId'], $columns);
            foreach ($columns as $subjectId){
                //本年累计
                $childGrandTotalBalance += $this->yearMoney($subjectId, $month, $array['rule']);
                $childMonthBalance += $this->monthMoney($subjectId, $month, $array['rule']);
            }
            $grandTotalBalance = match ($array['symbol']) {
                '-' => $grandTotalBalance - $childGrandTotalBalance,
                default => $grandTotalBalance + $childGrandTotalBalance
            };
            $monthBalance = match ($array['symbol']) {
                '-' => $monthBalance - $childMonthBalance,
                default => $monthBalance + $childMonthBalance
            };
        }
        return ['balance' => $grandTotalBalance, 'monthBalance' => $monthBalance];
    }

    /**
     * 本年累计
     */
    public function yearMoney($subjectId, $month, $rule): float|int
    {
        $subjectBalance = new subjectBalanceClass();
        $company = query('company', "coid = '" . self::$coid . "'");
        $subject = query('subject', "id = '$subjectId'");
        $year = date('Y', strtotime($month . '-01'));
        $where = " and date_format(a.recordDate,'%Y') >= '$year' and date_format(a.recordDate,'%Y-%m') <= '$month'";
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        switch ($rule) {
            case '贷方发生额':
                $balance = $daiInit['money'];
                break;
            case '借方发生额':
                $balance = $jieInit['money'];
                break;
            case '期初余额':
                $initResult = $subjectBalance->initMoney($subject, $year . '-01-01');
                $balance = $initResult['jieMoney']?:$initResult['daiMoney'];
                break;
            default://发生额
                if ($subject['direction'] =='借'){
                    $balance=$jieInit['money']-$daiInit['money'];
                }else{
                    $balance=$daiInit['money']-$jieInit['money'];
                }
                break;
        }
        if ($year <= date('Y', strtotime($company['startDate'] . '-01'))) {
            //本年累计如果是账套启用年，则要加上期初的借贷方累计
            switch ($rule) {
                case '贷方发生额':
                    $balance += self::centToYuan($subject['loanMoney']);
                    break;
                case '借方发生额':
                    $balance += self::centToYuan($subject['borrowMoney']);
                    break;
                case '期初余额':
                    $initResult = $subjectBalance->initMoney($subject, $company['startDate'] . '-01');
                    $balance += $initResult['jieMoney']?:$initResult['daiMoney'];
                    break;
                default://发生额
                    if ($subject['direction'] =='借'){
                        $balance +=self::centToYuan($subject['borrowMoney'])-self::centToYuan($subject['loanMoney']);
                    }else{
                        $balance +=self::centToYuan($subject['loanMoney'])-self::centToYuan($subject['borrowMoney']);
                    }
                    break;
            }
        }
        return $balance;
    }

    /**
     * 本期金额
     */
    public function monthMoney($subjectId, $month, $rule): float|int
    {
        $where = " and date_format(a.recordDate,'%Y-%m') = '$month' and b.subjectId = '$subjectId'";
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.direction = '借' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.direction = '贷' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        $subject = query('subject',"id = '$subjectId'");
        switch ($rule) {
            case '贷方发生额':
                $balance = $daiInit['money'];
                break;
            case '借方发生额':
                $balance =$jieInit['money'];
                break;
            case '期初余额':
                $subjectBalance = new subjectBalanceClass();

                $initResult = $subjectBalance->initMoney($subject, $month);
                $balance = $initResult['jieMoney']?:$initResult['daiMoney'];
                break;
            default://发生额
                if ($subject['direction'] =='借'){
                    $balance=$jieInit['money']-$daiInit['money'];
                }else{
                    $balance=$daiInit['money']-$jieInit['money'];
                }
                break;
        }
        return $balance;
    }

    public function printPage()
    {
        $month = static::rGet(self::$stid . self::page . 'Month');
        $assetObj = new assetDebtClass();
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $tr = [];
        $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
        $list = 0;
        $accountRule = companyClass::returnRule(1);
        foreach ($all['array'] as $array) {
            $list++;
            if (!in_array($array['name'], ['营业利润', '利润总额', '净利润','其他综合收益的税后净额','综合收益总额'])) {
                $result = $this->balance($array['name'], $month);
            } else {
                $result = $this->totalProfit($array['name'], $month,$accountRule);
            }
            $tr[] = ["<span style='font-weight: bold'>{$array['title']}</span>", $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];

            $res = $this->loopTr($array['name'], $list, $month, $assetObj);
            $tr = array_merge($tr, $res);
        }

        $tempHtml = '';
        foreach ($tr as $array) {
            $tempHtml .= "<tr class='have_border'>";
            for ($i = 0; $i <= 3; $i++) {
                $tempHtml .= "<td>{$array[$i]}</td>";
            }
            $tempHtml .= "</tr>";
        }

        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>利润表</div>
                 </div>
                 <div class='table-top-title'><div style='flex: 1'>编制单位：$company[name]</div><div style='flex: 1;text-align: center'>$month</div><div style='flex: 1;text-align: right'>单位：元</div></div>
              <table class='printTable' style='font-size: 13px'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>项目</td>
                   <td>行次</td>
                   <td>本年累计金额</td>
                   <td>本期金额</td>
                </tr>
                $tempHtml
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       $divHtml
                    </div>
                  <style>
                      .footer-ul-parent{float: right;margin-right: 10px}
                      .footer-ul li{margin-top: 10px}
                      .table-top-title{
                        height: 30px;
                        line-height: 30px;
                        font-size: 14px;
                        margin-top: 20px;
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                      }
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'portrait', ['padding' => "5mm 10mm 5mm 10mm"]);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $assetObj = new assetDebtClass();
            $accountRule = companyClass::returnRule(1);
            $assetObj->isExport = true;
            $month = static::rGet(self::$stid . self::page . 'Month');
            $title = array('项目', '行次', "本年累计金额", '本期金额');
            $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
            $list = 0;
            foreach ($all['array'] as $array) {
                $list++;
                if (!in_array($array['name'], ['营业利润', '利润总额', '净利润','其他综合收益的税后净额','综合收益总额'])) {
                    $result = $this->balance($array['name'], $month);
                } else {
                    $result = $this->totalProfit($array['name'], $month,$accountRule);
                }
                $tr[] = [$array['title'], $list, $result['balance'], $result['monthBalance']];
                $res = $this->loopTr($array['name'], $list, $month, $assetObj, true);
                $tr = array_merge($tr, $res);
            }
            $text = $this->control['name'] . "导出了利润表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "利润表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

}

